package cn.xspace.wnx.util;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;

import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;

import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;

import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.ConfirmDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.xspace.library.util.ContentType;
import cn.xspace.wnx.R;
import cn.xspace.wnx.db.ChatFileDao;
import cn.xspace.wnx.db.ChatRecordDao;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.chatui.bean.ChatFileEntity;
import cn.xspace.wnx.entity.GroupEntity;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.bean.OrgDeptUserBean;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/11/10.
 */

public class ForwardHelper {

    private static final String TAG = "ForwardHelper";
    private MsgRecordEntity msgRecordEntity;
    private static ForwardHelper helper;
    private MessageEntity messageEntity = null;
    private String keyId = "";
    private Context context;


    public static ForwardHelper getInstance() {
        if (helper == null) {
            helper = new ForwardHelper();
        }
        return helper;
    }

    public void confirmBeforeForward(Context mContext, ButtonClickListener rightListener, MsgRecordEntity recordEntity, String toWho) {
        context = mContext;
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(mContext)
                .setLeftText(mContext.getString(R.string.cancel))
                .setRightText(mContext.getString(R.string.button_ok))
                .setRightListener(rightListener)
                .setLeftListener(null);
        builder.setTitleVisible(View.VISIBLE);
        builder.setTitleMsg(String.format(mContext.getString(R.string.forward_to_who), toWho));
        if (recordEntity.msg_content_type == ContentType.PICTURE.toNumber()) {
            //图片
            boolean isLocal = false;
            if (new File(recordEntity.mFileEntity.file_url_local).exists()) {
                isLocal = true;
            }
            builder.setImageVisible(View.VISIBLE);
            if (isLocal) {
                builder.setImageSrc(recordEntity.mFileEntity.file_url_local, isLocal);
            } else {
                builder.setImageSrc(recordEntity.mFileEntity.file_url_remote, isLocal);
            }
            builder.setContentVisible(View.GONE);
        } else {
            String content = recordEntity.msg_content;
            if (recordEntity.msg_content_type == ContentType.OTHER.toNumber()) {
                String title = recordEntity.msg_content.split(Constants.CHAR_SPECIAL)[0];
                content = ContentType.OTHER.getTxt() + title;
            } else if (recordEntity.msg_content_type == ContentType.LOCATION.toNumber()) {
                content = ContentType.LOCATION.getTxt() + recordEntity.mFileEntity.address_desc;
            } else if (recordEntity.msg_content_type == ContentType.FILE.toNumber()) {
                content = ContentType.FILE.getTxt() + "\n" + recordEntity.mFileEntity.file_name;
            }
            builder.setContentMsg(content);
            builder.setContentVisible(View.VISIBLE);
            builder.setImageVisible(View.GONE);
        }
        builder.setListener();
        builder.show();

    }

    public void sendMessageRecordSingleChat(Context mContext, MsgRecordEntity recordEntity, OrgDeptUserBean userBean) {
        msgRecordEntity = recordEntity;
        msgRecordEntity.msg_type = MsgType.CHAT_SINGLE.toNumber();
        msgRecordEntity.msg_sender_name = userBean.user_name;
        msgRecordEntity.msg_sender_id = userBean.user_id;
        msgRecordEntity.msg_logo = userBean.user_logo;
        keyId = userBean.user_id;
        buildMessageListBean();
        sendBefore();
        Map sendMap = new HashMap<>();
        sendMap.put("user_id", MyInfoUtil.getMyUserid(mContext));
        sendMap.put("msg_type", recordEntity.msg_content_type);
        String url = Constants.sendHXSingleChatMsg;
        if (recordEntity.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            sendMap.put("msg_recevier_id", recordEntity.msg_sender_id);
        }
        sendMap.put("msg_text", recordEntity.msg_content);
        if (recordEntity.msg_content_type == ContentType.LOCATION.toNumber()) {
            sendMap.put("msg_lat", recordEntity.mFileEntity.lat);
            sendMap.put("msg_lng", recordEntity.mFileEntity.lng);
            sendMap.put("msg_postion", recordEntity.mFileEntity.address_desc);
            sendMap.put("msg_text", recordEntity.mFileEntity.file_url_remote);
        } else if (recordEntity.msg_content_type == ContentType.FILE.toNumber()) {
            sendMap.put("msg_name", recordEntity.mFileEntity.file_name);
            sendMap.put("msg_text", recordEntity.mFileEntity.file_url_remote);
        }
        RxUtil.getInstance().registerSubscription(OkHttpManager.getInstance().commonRequest(url, sendMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        commonSendFailedDeal();
                        Map<String, Object> fmap = new HashMap<String, Object>();
                        fmap.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                        EventBus.getDefault().post(fmap);
                        T.showShort(context, e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        T.showShort(context, context.getResources().getString(R.string.forward_success));
                        commonSendSuccessDeal(baseReturnBean);
                        Map<String, Object> fmap = new HashMap<String, Object>();
                        fmap.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                        EventBus.getDefault().post(fmap);
                    }
                }));
        //提交消息
    }

    public void sendMessageGroup(Context mContext, MsgRecordEntity recordEntity, GroupEntity groupEntity) {
        msgRecordEntity = recordEntity;
        msgRecordEntity.msg_type = MsgType.CHAT_CROUP.toNumber();
        msgRecordEntity.group_type = groupEntity.group_type;
        msgRecordEntity.msg_group_id = groupEntity.group_id;
        msgRecordEntity.msg_group_name = groupEntity.group_name;
        msgRecordEntity.msg_logo = groupEntity.group_logo;
        keyId = groupEntity.group_id;
        buildMessageListBean();
        sendBefore();
        Map sendMap = new HashMap<>();
        sendMap.put("user_id", MyInfoUtil.getMyUserid(mContext));
        sendMap.put("msg_type", recordEntity.msg_content_type);
        String url = Constants.sendMultiChatMsg;
        sendMap.put("group_id", groupEntity.group_id);
        sendMap.put("group_type", groupEntity.group_type);
        sendMap.put("msg_text", recordEntity.msg_content);
        if (recordEntity.msg_content_type == ContentType.LOCATION.toNumber()) {
            sendMap.put("msg_lat", recordEntity.mFileEntity.lat);
            sendMap.put("msg_lng", recordEntity.mFileEntity.lng);
            sendMap.put("msg_postion", recordEntity.mFileEntity.address_desc);
            sendMap.put("msg_text", recordEntity.mFileEntity.file_url_remote);
        } else if (recordEntity.msg_content_type == ContentType.FILE.toNumber()) {
            sendMap.put("msg_name", recordEntity.mFileEntity.file_name);
        }
        RxUtil.getInstance().registerSubscription(OkHttpManager.getInstance().commonRequest(url, sendMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        commonSendFailedDeal();
                        Map<String, Object> fmap = new HashMap<String, Object>();
                        fmap.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                        EventBus.getDefault().post(fmap);
                        T.showShort(context, e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        T.showShort(context, context.getResources().getString(R.string.forward_success));
                        commonSendSuccessDeal(baseReturnBean);
                        Map<String, Object> fmap = new HashMap<String, Object>();
                        fmap.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                        EventBus.getDefault().post(fmap);
                    }
                }));
        //提交消息


    }

    public void sendMessageRecord(Context mContext, MsgRecordEntity recordEntity, String keyId, int chatType, String groupName) {
        msgRecordEntity = recordEntity;
        msgRecordEntity.msg_type = chatType;
        if (chatType == MsgType.CHAT_SINGLE.toNumber()) {
            msgRecordEntity.msg_sender_id = keyId;
        } else if (chatType == MsgType.CHAT_CROUP.toNumber()) {
            msgRecordEntity.msg_group_id = keyId;
            msgRecordEntity.msg_group_name = groupName;
        }
        buildMessageListBean();
        sendBefore();
        Map sendMap = new HashMap<>();
        sendMap.put("user_id", MyInfoUtil.getMyUserid(mContext));
        sendMap.put("msg_type", recordEntity.msg_content_type);
        String url = Constants.sendHXSingleChatMsg;
        if (recordEntity.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            sendMap.put("msg_recevier_id", recordEntity.msg_sender_id);
        } else if (recordEntity.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            sendMap.put("group_id", recordEntity.msg_group_id);
            url = Constants.sendMultiChatMsg;
            sendMap.put("group_type", msgRecordEntity.group_type);
        }
        sendMap.put("msg_text", recordEntity.msg_content);
        if (recordEntity.msg_content_type == ContentType.LOCATION.toNumber()) {
            sendMap.put("msg_lat", recordEntity.mFileEntity.lat);
            sendMap.put("msg_lng", recordEntity.mFileEntity.lng);
            sendMap.put("msg_postion", recordEntity.mFileEntity.address_desc);
        } else if (recordEntity.msg_content_type == ContentType.FILE.toNumber()) {
            sendMap.put("msg_name", recordEntity.mFileEntity.file_name);
        }

        //提交消息
        RxUtil.getInstance().registerSubscription(OkHttpManager.getInstance().commonRequest(url, sendMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        commonSendFailedDeal();
                        Map<String, Object> fmap = new HashMap<String, Object>();
                        fmap.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                        EventBus.getDefault().post(fmap);
                        T.showShort(context, e.getMessage());
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        T.showShort(context, context.getResources().getString(R.string.forward_success));
                        commonSendSuccessDeal(baseReturnBean);
                        Map<String, Object> fmap = new HashMap<String, Object>();
                        fmap.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                        EventBus.getDefault().post(fmap);
                    }
                }));

    }

//    Subscriber<BaseReturnBean> chatSub = ;

    private void commonSendSuccessDeal(BaseReturnBean baseReturnBean) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(baseReturnBean.data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String msg_id = jsonObject.optString("msg_id");
        final String msg_time = jsonObject.optString("msg_time");


        msgRecordEntity.msg_send_status = MessageEntity.MsgSendStatus.SUCCESS.toNumber();
        //发送成功的记录，如果列表不是此条对应的记录，则不需更新
//            MessageEntity msgEntity = MessageRecordDao.getInstance().getMessageEntityByKeyId(message.msg_sender_id);

        RxUtil.getInstance().registerSubscription(MessageRecordDao.getInstance().getiMessageData()
                .updateMessageEntityStatus(keyId, MessageEntity.MsgSendStatus.SUCCESS.toNumber(), msgRecordEntity.msg_type)
                .subscribeOn(Schedulers.io())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtil.d(s);
                    }
                }));

        RxUtil.getInstance().registerSubscription(MessageRecordDao.getInstance().getiMessageData()
                .updateMessageLastTime(keyId, msg_time, msgRecordEntity.msg_type)
                .subscribeOn(Schedulers.io())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtil.d(s);
                    }
                }));
        //并且更新为最新时间


        //更新消息列表的最新发送状态
//        MessageRecordDao.getInstance().getiMessageData().getMessageEntityByKeyId(keyId, msgRecordEntity.msg_type)
//                .subscribeOn(Schedulers.io())
//                .subscribe(new Action1<MessageEntity>() {
//                    @Override
//                    public void call(MessageEntity entity) {
//
//                        if (entity != null && msgRecordEntity.msg_last_time != null && msgRecordEntity.msg_last_time.equals(entity.msg_last_time)) {
//                            LogUtil.d(entity.msg_last_time);
//                            //对应是，更新状态
////                MessageRecordDao.getInstance().updateMessageEntityStatus(message.msg_sender_id, MessageEntity.MsgSendStatus.SUCCESS.toNumber());
//
//                        }
//                    }
//                });
//更新消息记录状态
        RxUtil.getInstance().registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateMsgRecordSendStatus(msgRecordEntity.inserttime, MessageEntity.MsgSendStatus.SUCCESS.toNumber())
                .subscribeOn(Schedulers.io())
                .subscribe()
        );

        RxUtil.getInstance().registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateLastTime(msgRecordEntity.inserttime, msg_time)
                .subscribeOn(Schedulers.io())
                .subscribe());

        msgRecordEntity.msg_id = msg_id;
        msgRecordEntity.msg_last_time = msg_time;
        RxUtil.getInstance().registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateMsgRecordMsgId(msgRecordEntity.inserttime, msg_id)
                .subscribeOn(Schedulers.io())
                .subscribe());

//        ChatRecordDao.getInstance().updateMsgRecordMsgId(message.inserttime, msg_id);
        if (ChatFileEntity.isNeedSaveFile(msgRecordEntity.msg_content_type)) {
            String remote_url = jsonObject.optString("msg_text");

            if (!TextUtils.isEmpty(remote_url)) {
                msgRecordEntity.mFileEntity.file_url_remote = remote_url;
            }
//            ChatFileDao.getInstance().updateFileMsgIdPath(message.inserttime, message.msg_id);
            RxUtil.getInstance().registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileMsgIdPath(msgRecordEntity.inserttime, msgRecordEntity.msg_id)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe());

//            ChatFileDao.getInstance().updateFileRemotePathByTime(message.inserttime, message.mFileEntity.file_url_remote);
            RxUtil.getInstance().registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileRemotePathByTime(msgRecordEntity.inserttime, msgRecordEntity.mFileEntity.file_url_remote)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe());

        }


    }

    private void commonSendFailedDeal() {
        RxUtil.getInstance().registerSubscription(MessageRecordDao.getInstance().getiMessageData()
                .updateMessageEntityStatus(keyId, MessageEntity.MsgSendStatus.FAILED.toNumber(), msgRecordEntity.msg_type)
                .subscribeOn(Schedulers.io())
                .subscribe());
        RxUtil.getInstance().registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateMsgRecordSendStatus(msgRecordEntity.inserttime, MessageEntity.MsgSendStatus.FAILED.toNumber())
                .subscribeOn(Schedulers.io())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {

                    }
                }));
    }

    private void sendBefore() {
        msgRecordEntity.msg_id = "";
        RxUtil.getInstance().registerSubscription(MessageRecordDao.getInstance().getiMessageData().updateMessageList(messageEntity)
                .observeOn(Schedulers.io())
                .subscribe());
        //更新消息列表o
        //插入消息记录
        RxUtil.getInstance().registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation().insertMsgRecord(msgRecordEntity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe());


    }

    private void buildMessageListBean() {
        messageEntity = new MessageEntity();
        messageEntity.isRead = true;
        messageEntity.msg_content_type = msgRecordEntity.msg_content_type;
        messageEntity.msg_logo = msgRecordEntity.msg_logo;
        messageEntity.msg_type = msgRecordEntity.msg_type;
        messageEntity.msg_send_status = MessageEntity.MsgSendStatus.NOT_SEND.toNumber();
        if (msgRecordEntity.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            messageEntity.msg_group_id = msgRecordEntity.msg_group_id;
            messageEntity.group_type = msgRecordEntity.group_type;
            messageEntity.msg_group_name = msgRecordEntity.msg_group_name;
        } else if (msgRecordEntity.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            messageEntity.msg_sender_id = msgRecordEntity.msg_sender_id;
            messageEntity.msg_sender_name = msgRecordEntity.msg_sender_name;
        }
        messageEntity.msg_last_time = DateUtils.getNowDateTime();
        messageEntity.msg_content = ChatFileEntity.getContentByType(msgRecordEntity.msg_content, msgRecordEntity.msg_content_type);

        msgRecordEntity.msg_send_status = MessageEntity.MsgSendStatus.NOT_SEND.toNumber();
        msgRecordEntity.is_mine = "1";
        msgRecordEntity.inserttime = System.currentTimeMillis() + "";
    }
}
